<?php

/**
 * 发票与回款对应关系仓库
 * @author wangwx 2015-5-12
 */

namespace common\repositories\myhtsq;

use common\entities\myhtsq\ContractPaymentEntity;
use common\repositories\common\MyscrmContractSyncDeleteDataRepository;
use Exception;
use common\repositories\BaseRepository;
use common\support\StringHelper;
use common\error\ErrorCode;
use common\entities\myhtsq\InvoicePaymentEntity;

class InvoicePaymentRepository extends BaseRepository {

    /**
     * 构造方法
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 根据 发票与应收款关系ID 删除对应的 回款与发票及应收款对应关系记录
     * @param string $invoiceReceivableId 发票与应收款关系ID
     * @return boolean
     */
    public static function deleteInvoicePaymentByInvoiceReceivableId($invoiceReceivableId)
    {
        /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
        $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

        $deleteData = InvoicePaymentEntity::findAll(['invoice_receivable_id' => $invoiceReceivableId]);

        $deleteResult = InvoicePaymentEntity::deleteAll(['invoice_receivable_id' => $invoiceReceivableId]);

        if ($deleteResult > 0) {
            foreach ($deleteData as $data) {
                $contractSyncDeleteDataRepository->add('myscrm_invoice_payment', 'invoice_payment_id', $data['invoice_payment_id']);
            }
        }

        if ($deleteResult === false) {
            return $deleteResult;
        }

        return $deleteResult;
    }

    /**
     * 根据应收款ID获取对应的回款金额
     * @param string $receivableId
     * @return float
     */
    public static function getTotalPaymentAmountByReceivableId($receivableId) {
        $totalPaymentAmount = 0;

        $query = InvoicePaymentEntity::find()
                ->select('myscrm_invoice_payment.*')
                ->innerJoin('myscrm_invoice_receivable', 'myscrm_invoice_payment.invoice_receivable_id = myscrm_invoice_receivable.invoice_receivable_id')
                ->where(['receivable_id' => $receivableId])
                ->asArray()
                ->all();

        if (isset($query) && count($query) > 0) {
            foreach ($query as $k => $v) {
                if (isset($v['cur_payment_amount']) && !empty($v['cur_payment_amount'])) {
                    $totalPaymentAmount += floatval($v['cur_payment_amount']);
                }
            }
        }

        return $totalPaymentAmount;
    }

    /**
     * 保存回款与发票及应收款对应关系
     * @param \common\models\myhtsq\InvoicePaymentModel $invoicePaymentModel
     * @return boolean|string   失败|关系Guid
     */
    public static function addInvoicePayment($invoicePaymentModel) {
        try {
            $entity = new InvoicePaymentEntity();
            $entity->invoice_payment_id = StringHelper::uuid();
            $entity->invoice_receivable_id = $invoicePaymentModel['invoice_receivable_id'];
            $entity->payment_id = $invoicePaymentModel['payment_id'];
            $entity->cur_payment_amount = floatval($invoicePaymentModel['cur_payment_amount']);

            $result = $entity->save();
            if ($result === FALSE) {
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 根据发票id获取对应的回款总额
     * @param string $invoiceId 发票ID
     * @return float
     */
    public static function getTotalPaymentAmountByInvoiceId($invoiceId) {
        $totalPaymentAmount = 0;

        $query = InvoicePaymentEntity::find()
                ->select('myscrm_invoice_payment.*')
                ->innerJoin('myscrm_invoice_receivable', 'myscrm_invoice_payment.invoice_receivable_id = myscrm_invoice_receivable.invoice_receivable_id')
                ->where(['myscrm_invoice_receivable.invoice_id' => $invoiceId])
                ->asArray()
                ->all();

        if (isset($query) && count($query) > 0) {
            foreach ($query as $k => $v) {
                if (isset($v['cur_payment_amount']) && !empty($v['cur_payment_amount'])) {
                    $totalPaymentAmount += floatval($v['cur_payment_amount']);
                }
            }
        }

        return $totalPaymentAmount;
    }

    /**
     * 获取合同的回款总额
     * @param $contractId
     */
    public static function getTotalPaymentAmountByContractId($contractId){
        $query = InvoicePaymentEntity::find()
            ->select('sum(myscrm_invoice_payment.cur_payment_amount)')
            ->innerJoin('myscrm_contract_payment', 'myscrm_contract_payment.payment_id=myscrm_invoice_payment.payment_id')
            ->where(['myscrm_contract_payment.contract_id'=>$contractId])
            ->scalar();
        return empty($query)? 0 : $query;
    }

    /**
     * 根据发票与应收款对应关系ID 获取对应的 回款与发票及应收款对应关系
     * @param string $invoiceReceivableId 发票与应收款对应关系ID
     * @return array 
     */
    public static function getInvoicePaymentByInvoiceReceivableId($invoiceReceivableId) {
//        $sql = 'select myscrm_invoice_payment.*,myscrm_contract_payment.finance_code
//                from myscrm_invoice_payment
//                left join myscrm_contract_payment on myscrm_invoice_payment.payment_id = myscrm_contract_payment.payment_id';
//        $query = InvoicePaymentEntity::findBySql($sql)
//                ->where(['myscrm_invoice_payment.invoice_receivable_id' => $invoiceReceivableId])
//                ->asArray()
//                ->all();
        
        $query = InvoicePaymentEntity::find()
                ->select('myscrm_invoice_payment.*,myscrm_contract_payment.finance_code')
                ->leftJoin('myscrm_contract_payment', 'myscrm_invoice_payment.payment_id = myscrm_contract_payment.payment_id')
                ->where(['myscrm_invoice_payment.invoice_receivable_id' => $invoiceReceivableId])
                ->asArray()
                ->all();

        return $query;
    }

    /**
     * 根据回款ID 获取对应的 回款与发票及应收款对应关系
     * @param string $paymentId 回款ID
     * @return array 
     */
    public static function getInoicePaymentByPaymentId($paymentId) {
//        $sql = 'select myscrm_invoice_payment.*,myscrm_invoice.invoice_code,myscrm_invoice.invoice_no,myscrm_invoice_receivable.invoice_id,myscrm_invoice_receivable.receivable_id
//                    from myscrm_invoice_payment
//                    left join myscrm_invoice_receivable on myscrm_invoice_payment.invoice_receivable_id = myscrm_invoice_receivable.invoice_receivable_id
//                    left join myscrm_invoice on myscrm_invoice_receivable.invoice_id = myscrm_invoice.invoice_id';
//        $query = InvoicePaymentEntity::findBySql($sql)
//                ->where(['myscrm_invoice_payment.payment_id' => $paymentId])
//                ->asArray()
//                ->all();

        $query = InvoicePaymentEntity::find()
                ->select('myscrm_invoice_payment.*,myscrm_invoice.invoice_code,myscrm_invoice.invoice_no,myscrm_invoice_receivable.invoice_id,myscrm_invoice_receivable.receivable_id')
                ->leftJoin('myscrm_invoice_receivable', 'myscrm_invoice_payment.invoice_receivable_id = myscrm_invoice_receivable.invoice_receivable_id')
                ->leftJoin('myscrm_invoice', 'myscrm_invoice_receivable.invoice_id = myscrm_invoice.invoice_id')
                ->where(['myscrm_invoice_payment.payment_id' => $paymentId])
                ->asArray()
                ->all();

        return $query;
    }

    /**
     *  删除指定 回款与发票及应收款对应关系id 的记录
     * @param type $invoicePaymentId 回款与发票及应收款对应关系id
     * @return boolean| Description
     */
    public static function deleteInvoicePaymentByInvoicePaymentId($invoicePaymentId)
    {
        /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
        $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

        $deleteResult = InvoicePaymentEntity::deleteAll(['invoice_payment_id' => $invoicePaymentId]);

        if ($deleteResult > 0) {
            $contractSyncDeleteDataRepository->add('myscrm_invoice_payment', 'invoice_payment_id', $invoicePaymentId);
        }

        if ($deleteResult === false) {
            return $deleteResult;
        }

        return $deleteResult;
    }

    /**
     * 根据发票ID获取已关联的回款列表
     * @param $invoiceId
     * @return array
     */
    public static function getInvoicePaymentInfoByInvoiceId($invoiceId)
    {
        return InvoicePaymentEntity::find()
            ->select('myscrm_invoice_payment.*, myscrm_invoice_receivable.invoice_id, myscrm_invoice_receivable.receivable_id,myscrm_contract_payment.payment_code,myscrm_contract_payment.payment_date,myscrm_contract_payment.payment_account_name')
            ->leftJoin('myscrm_invoice_receivable', 'myscrm_invoice_payment.invoice_receivable_id = myscrm_invoice_receivable.invoice_receivable_id')
            ->leftJoin('myscrm_contract_payment', 'myscrm_contract_payment.payment_id=myscrm_invoice_payment.payment_id')
            ->where(['myscrm_invoice_receivable.invoice_id' => $invoiceId])
            ->asArray()
            ->all();
    }

    /**
     * 获取所有列表
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getAllList()
    {
        return InvoicePaymentEntity::find()
            ->asArray()
            ->all();
    }

    public function getSumPaymentByContractId($contractId)
    {
        return ContractPaymentEntity::find()
            ->select('SUM(payment_amount) as payment_amount')
            ->where(['contract_id' => $contractId])
            ->scalar();
    }

}
